#define _CRT_SECURE_NO_WARNINGS 1
#include "Stack.h"

void STCheckCapacity(ST* ps)
{
	assert(ps);
	if (ps->capacity == ps->top)
	{
		int newCapacity = ps->capacity == 0 ? 4 : 2 * (ps->capacity);
		STDataType* tmp = (STDataType*)realloc(ps->arr, sizeof(STDataType) * newCapacity);
		if (tmp == NULL)
		{
			perror("realloc fail!");
			exit(1);
		}
		ps->arr = tmp;
		ps->capacity = newCapacity;
	}
}

void STInit(ST* ps)
{
	ps->arr = NULL;
	ps->top = ps->capacity = 0;
}

void STDestroy(ST* ps)
{
	if (ps->arr)
		free(ps->arr);

	ps->arr = NULL;
	ps->capacity = ps->top = 0;
}

void STPush(ST* ps, STDataType x)
{
	STCheckCapacity(ps);
	ps->arr[ps->top++] = x;
}

bool STEmpty(ST* ps)
{
	assert(ps);
	return ps->top == 0;
}

void STPop(ST* ps)
{
	assert(!STEmpty(ps));
	ps->top--;
}

STDataType STTop(ST* ps)
{
	assert(!STEmpty(ps));
	return ps->arr[(ps->top) - 1];
}

int STSize(ST* ps)
{
	assert(ps);
	return ps->top;
}

void STPrint(ST* ps)
{
	ST* pcur = ps;
	for(int i=0;i<ps->top;i++)
	{
		printf("%d ->", ps->arr[i]);
	}
	printf("NULL\n");
}